import React, { useEffect, useState } from 'react';
import { Form, Button, Typography, Flex, message, Col, Table } from 'antd';
import { useTranslation } from 'react-i18next';
import RequestFormProjectTpl from '../../Components/RequestFormProjectTpl';
import RequestFormProductTpl from '../../Components/RequestFormProductTpl';
import { useLocation, useNavigate } from 'react-router-dom';
import { apiSysTemplateInitiate } from '../../../services/common';
import { apiBigSimulationFileAdd, apiBigSimulationFileView, apiBigSimulationFileEdit } from '../../../services/bigSimulationFile/request';
import { ACCEPT_TYPE, REQUEST_PAGE, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import { getUserName, formatRequestItemData } from '../../../utils/commonUtil';
import _ from 'lodash';
import RequestApprovalBtn from '../../Components/RequestApprovalBtn';
import BigFileUpload from '../../Components/BigFileUpload';
import FileAnalysisContent from '../Components/FileAnalysisContent';

const { Title } = Typography;
const BigSimulationFileRequestDetails = () => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const location = useLocation();
  if (!location?.state) {
    navigate('/bigSimulationFile/list');
  };
  const queryParams = location?.state || {};
  const { tplId, tBu, bigFileProjectId, editMode, approveRequestSituationId, tMd, tTm } = queryParams;
  const [initialValues, setInitialValues] = useState();


  // mock permission
  const isCampAdmin = true;
  const isBuPRPD = false;
  const isBuAdmin = false;
  const isBuTester = false;

  const apiBigSimulationFileSaveAsync = async (type) => {
    const formData = form?.getFieldsValue();
    const prjData = {
      product: formData?.product,
      project: formData?.project,
      userId: getUserName(),
      operationType: type,
    };
    const data = editMode === RES_MODE.NEW ? await apiBigSimulationFileAdd(prjData) : await apiBigSimulationFileEdit(prjData);
    // console.log(data);
    if (data?.data?.code === 200) {
      message.success(t('common.saveSuccess'));
      navigate('/bigSimulationFile/list')
    }
  };
  const saveClickHandle = (type) => {
    // console.log(form.getFieldsValue());
    form.validateFields().then(() => {
      apiBigSimulationFileSaveAsync(type);
    }, () => {
      return false;
    });
  };

  // 大文件部分
  const productExtraContentrRender = (index) => {
    const listNames = 'product';
    return (
      <>
        <Col span={24}>
          <BigFileUpload
            btnText={t('bigSimulationFile.uploadBtnText')}
            acceptType={ACCEPT_TYPE.ALL}
            disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
            bigFileProductId={initialValues?.project?.bigFileProjectId?.fieldValue}
            uploadUpdateFn={(fileData) => {
              const productData = form?.getFieldsValue()?.[listNames];
              const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
              productData[index] = {
                ...productItemData,
                attachmentUrl: `${productItemData?.bigFileProductId?.fieldValue}_${fileData?.md5}`,
              };
              form.setFieldsValue({
                [listNames]: productItemData,
              });
            }}
          />
        </Col>
        {
          form?.getFieldsValue()?.[listNames]?.[index]?.analysisContents?.length > 0 &&
          <FileAnalysisContent analysisContents={form?.getFieldsValue()?.[listNames]?.[index]?.analysisContents} />
        }
      </>
    )
  };

  useEffect(() => {
    // 获取模板数据
    let initData = {};
    if (tplId && editMode === RES_MODE.NEW) {
      apiSysTemplateInitiate({ templateName: tTm, buType: tBu, moduleName: tMd }).then((res) => {
        if (res?.data?.code === 200) {
          initData = {
            project: res?.data?.data?.Project,
            product: [
              {
                ...res?.data?.data?.Product
              }
            ]
          };
          setInitialValues(initData);
        }
      })
    } else if (bigFileProjectId && (editMode === RES_MODE.APPROVAL || editMode === RES_MODE.VIEW || editMode === RES_MODE.EDIT || editMode === RES_MODE.TESTEREDIT)) {
      apiBigSimulationFileView({
        bigFileProjectId: bigFileProjectId,
        userId: getUserName(),
      }).then((res) => {
        if (res?.data?.code === 200) {
          const newProject = formatRequestItemData(res?.data?.data?.item?.project);
          const newProduct = res?.data?.data?.item?.product?.map((prdItem) => {
            return formatRequestItemData(prdItem)
          });
          initData = {
            project: newProject,
            product: newProduct,
          };
          setInitialValues(initData);
        }
      })
    };
  }, []);

  return (
    <>
      {
        initialValues &&
        <>
          <div className='page-title-wrap'>
            <Flex align='center' justify='space-between'>
              <Title className='fontStyleH2' level={2} >{editMode === RES_MODE.NEW ? t(`common.newRequest`) : t(`common.requestDetail`)}</Title>
              <div>
                <RequestApprovalBtn
                  approveRequestSituationId={approveRequestSituationId}
                  form={form}
                  moduleConfig={REQUEST_PAGE['Big Simulation File']}
                  initialValues={initialValues}
                  editMode={editMode}
                />
                {
                  (
                    //可填写测试数据 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin || isBuTester) && initialValues?.project?.requestStatus?.fieldValue === APPROVED) ||
                    //可重新编辑 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || initialValues?.project?.requestStatus?.fieldValue === APPROVED || editMode === RES_MODE.NEW))
                  ) && editMode !== RES_MODE.VIEW &&
                  <Button onClick={() => { saveClickHandle('save') }} style={{ marginRight: '10px' }}>{t('common.save')}</Button>
                }
                {

                  //可重新编辑 submit
                  (isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || editMode === RES_MODE.NEW) && editMode !== RES_MODE.VIEW &&
                  <Button type='primary' onClick={() => { saveClickHandle('submit') }}>{t('common.submit')}</Button>
                }
              </div>
            </Flex>
          </div>
          <div className='page-content-wrap'>
            <Form form={form}
              initialValues={initialValues}
              disabled={editMode === RES_MODE.VIEW || editMode === RES_MODE.TESTEREDIT || editMode === RES_MODE.APPROVAL}
            >
              {/* Project */}
              <RequestFormProjectTpl
                uploadParams={{ type: 'bigSimulationFile', name: 'project' }}
                tplData={queryParams}
                listNames='project'
                form={form}
                initialValues={initialValues}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Big Simulation File']}
              />
              {/* Product */}
              <RequestFormProductTpl
                uploadParams={{ type: 'bigSimulationFile', name: 'product' }}
                listNames='product'
                form={form}
                initialValues={initialValues}
                productExtraContentrRender={productExtraContentrRender}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Big Simulation File']}
              />
            </Form>
          </div>
        </>
      }
    </>
  )
};

export default BigSimulationFileRequestDetails;
